/*
 * Copyright (C) 2020 ActiveJ LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.activej.cube.aggregation.predicate.impl;

import io.activej.codegen.expression.Expression;
import io.activej.common.annotation.ExposedInternals;
import io.activej.cube.aggregation.predicate.AggregationPredicate;

import java.util.Map;
import java.util.Set;

import static io.activej.codegen.expression.Expressions.*;
import static io.activej.common.Checks.checkNotNull;
import static io.activej.cube.aggregation.predicate.AggregationPredicates.alwaysFalse;
import static io.activej.cube.aggregation.predicate.AggregationPredicates.eq;

@ExposedInternals
public final class Between implements AggregationPredicate {
	public final String key;
	public final Comparable<Object> from;
	public final Comparable<Object> to;

	public Between(String key, Comparable<Object> from, Comparable<Object> to) {
		this.key = checkNotNull(key);
		this.from = checkNotNull(from);
		this.to = checkNotNull(to);
	}

	@Override
	public AggregationPredicate simplify() {
		return (from.compareTo(to) > 0) ? alwaysFalse() : (from.equals(to) ? eq(key, from) : this);
	}

	@Override
	public Set<String> getDimensions() {
		return Set.of(key);
	}

	@Override
	public Map<String, Object> getFullySpecifiedDimensions() {
		return Map.of();
	}

	@Override
	public Expression createPredicate(Expression record, ValueResolver valueResolver) {
		Expression property = valueResolver.getProperty(record, key);
		return and(isNotNull(property),
			isGe(property, value(valueResolver.transformArg(key, from))),
			isLe(property, value(valueResolver.transformArg(key, to))));
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		Between that = (Between) o;

		if (!key.equals(that.key)) return false;
		if (!from.equals(that.from)) return false;
		return to.equals(that.to);

	}

	@Override
	public int hashCode() {
		int result = key.hashCode();
		result = 31 * result + from.hashCode();
		result = 31 * result + to.hashCode();
		return result;
	}

	@Override
	public String toString() {
		return key + " BETWEEN " + from + " AND " + to;
	}
}
